package com.zxc.controller.admin;

import com.zxc.controller.util.AjaxResult;
import com.zxc.controller.util.ListReflect;
import com.zxc.model.*;
import com.zxc.service.*;
import com.zxc.service.impl.CourseServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.jsp.tagext.PageData;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin/online")
public class OnlineExamController{
    private Logger log = LoggerFactory.getLogger(OnlineExamController.class);
    @Autowired
    QuestionService questionService;
    @Resource
    private PageService pageService;
    @Autowired
    OnlineExamService onlineExamService;
    @Autowired
    OnlineExamQuestionService onlineExamQuestionService;
    @Autowired
    CourseService courseService;
    @Autowired
    OnlineExamCourseRecordService onlineExamCourseRecordService;
    @Autowired
    OnlineExamStudentService onlineExamStudentService;

    @RequestMapping("/subject")
    public String subject(@Param("page") int page, Model model) {
        try {
            List<Question> questions = questionService.findQuestionList(new Question(), page, 4);
            model.addAttribute("paging",  pageService.setList(page, 4, questionService.queryAllCount(), questions));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "admin/online/subject";
    }
    @RequestMapping(value = "/subjectAdd", method = RequestMethod.GET)
    public String subjectAdd() {
        return "admin/online/subjectAdd";
    }

    @RequestMapping(value = "/examAdd", method = RequestMethod.GET)
    public String examtAdd() {
        return "admin/online/examAdd";
    }

    /**
     * 发布考试
     * @return
     */
    @RequestMapping(value = "/sendExam", method = RequestMethod.GET)
    public String sendExam(Integer examId, Model model) {
        List<Course> courseList = courseService.queryAllCourse();
        model.addAttribute("courseList", courseList);
        model.addAttribute("examId", examId);
        return "admin/online/sendExam";
    }

    @RequestMapping(value = "/subjectAdd", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addSave(@RequestBody Question question) {
        try {
            int flag = questionService.insert(question);
            log.info("flag:" + flag);
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success("成功");
    }

    @RequestMapping(value = "/examAdd", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult examAddPost(@RequestBody OnlineExam exam) {
        try {
            exam.setScore(0D);
            int flag = onlineExamService.insert(exam);
            log.info("flag:" + flag);
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success("成功");
    }


    @RequestMapping(value = "/getExamRecord", method = RequestMethod.GET)
    public String getExamRecord(Integer examId, Model model) {
        List<OnlineExamCourseRecord> onlineExamCourseRecords = onlineExamCourseRecordService.queryByExamId(examId);
        model.addAttribute("onlineExamCourseRecords", onlineExamCourseRecords);
        return "admin/online/getExamRecord";
    }

    @RequestMapping(value = "/sendExam", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult sendExamPost(Integer classId, Integer examId) {
        List<Student> studentList = courseService.queryStuByCourseId(classId);
        for (int i = 0; i < studentList.size(); i++) {
            OnlineExamStudent onlineExamStudent = new OnlineExamStudent();
            onlineExamStudent.setExamId(examId);
            onlineExamStudent.setStudentId(studentList.get(i).getStuId());
            onlineExamStudentService.insert(onlineExamStudent);
        }
        // 写发布记录
        Course course =  courseService.queryCourse(classId);
        OnlineExamCourseRecord onlineExamCourseRecord = new OnlineExamCourseRecord();
        onlineExamCourseRecord.setClassId(classId);
        onlineExamCourseRecord.setClassName(course.getClassName());
        onlineExamCourseRecord.setExamId(examId);
        onlineExamCourseRecord.setCreateTime(new Date());
        onlineExamCourseRecordService.insert(onlineExamCourseRecord);

        return AjaxResult.success("成功");
    }

    @RequestMapping(value = "/examAddSubject", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult examAddSubject(String ids, Integer examId) {
        String[] idsArray = ids.split(",");
//        List<String> idList = Arrays.stream(idsArray).collect(Collectors.toList());
        Double totalScore = 0.0;
        for (int i = 0; i < idsArray.length; i++) {
            OnlineExamQuestion onlineExamQuestion = new OnlineExamQuestion();
            onlineExamQuestion.setExamId(examId);
            Integer questionId = Integer.parseInt(idsArray[i]);
            onlineExamQuestion.setQuestionId(questionId);
            Question question = questionService.queryById(questionId);
            totalScore = totalScore + question.getScore();

            onlineExamQuestionService.insert(onlineExamQuestion);
        }
        // 更新试卷总分
        OnlineExam onlineExam = new OnlineExam();
        onlineExam.setExamId(examId);
        onlineExam.setScore(totalScore);
        onlineExamService.updateScore(onlineExam);

        return AjaxResult.success("成功");
//        return toAjax(questionService.insert(question));
    }

    @RequestMapping("/exam")
    public String exam(@Param("page") int page, Model model) {
        try {
            OnlineExam onlineExam = new OnlineExam();
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", null);
            params.put("endTime", null);
            onlineExam.setParams(params);
            List<OnlineExam> onlineExams = onlineExamService.findOnlineExamList(onlineExam);
            System.out.println(onlineExams.get(0).getExamStartDate());
            model.addAttribute("paging", pageService.subList(page, 4, onlineExams));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "admin/online/exam";
    }

    @RequestMapping("/examDetail")
    public String examDetail(@Param("page") int page,@Param("examId") int examId, Model model) {
        try {
            OnlineExam onlineExam = onlineExamService.queryById(examId);
            List<Question> questions = questionService.findQuestionList(new Question(), page, 4);
            Page pageData = pageService.setList(page, 4, questionService.queryAllCount(), questions);

            pageData.setTotalPage(questionService.queryAllCount());

            Integer[] ids = onlineExam.getIds();
            Set<Integer> idSet = Arrays.stream(ids).collect(Collectors.toSet());

            List<Question> itemQuestins = (List<Question>) pageData.getDataList();
            for (int i = 0; i < itemQuestins.size(); i++) {
                if ( idSet.contains(itemQuestins.get(i).getId())) {
                    itemQuestins.get(i).setIsChoose(1);
                }
            }

            model.addAttribute("onlineExam", onlineExam);
            model.addAttribute("idsLenght", onlineExam.getIds().length);
            model.addAttribute("paging", pageData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "admin/online/examDetail";

    }

}


